#!/usr/bin/env python

from __future__ import with_statement
import sys, math, linecache,  thread, os
from klasses import *
from pawrap import *
try:
 	import pygtk
  	pygtk.require("2.0")
except:
  	pass
try:
	import gtk
  	import gtk.glade
except:
	sys.exit(1)
	

def traceit(frame, event, arg):
    if event == "line":
        lineno = frame.f_lineno
        filename = frame.f_globals["__file__"]
        if filename == "<stdin>":
            filename = "glade.py"
        if (filename.endswith(".pyc") or
            filename.endswith(".pyo")):
            filename = filename[:-1]
        name = frame.f_globals["__name__"]
        line = linecache.getline(filename, lineno)
        print "%s:%s: %s" % (name, lineno, line.rstrip())
    else:
        print event,arg
    return traceit

def getlibpath(file):
    for i in sys.path:
        #print i+file
        if os.path.exists(i+file):
            return i+file

class Gui:

    def __init__(self):
        #Set the Glade file
        self.gladefile = getlibpath("/pavol/gui.glade")
        self.wTree = gtk.glade.XML(self.gladefile)
        #Get the Main Window, and connect the "destroy" event
        self.window = self.wTree.get_widget("pulsevolwin")
        if (self.window):
            self.window.connect("destroy", self.destroy)
        self.hbox = self.wTree.get_widget("hbox1")
        
        self.window.resize(160,280)
        self.window.set_size_request(160,280)
        self.pulse = Pulse("PulseVol",self.event_cb)
        print self.pulse.version()
        self.widgets={}
        self.lock = thread.allocate_lock()
        
        #print "User:",self.p.server_info.user_name
        
    def addsink(self,idx):
        tmp = WHolder(idx,self.sb_valchanged)
        v = self.pulse.sinks[idx]
        #tmp.set_label(self.pulse.clients[v.client].name+" [#"+"%d"%idx+"] ")
        #tmp.set_desc(v.name)
        #tmp.set_sbvalue(v.volume.values[0])
        self.widgets[idx] = tmp
        self.hbox.pack_start(tmp.get_widget(),True,True,0)
        self.changesink(idx)
    
    def removesink(self,idx):
        self.hbox.remove( self.widgets[idx].get_widget() )
        del self.widgets[idx]
        
    def changesink(self,idx):
        #print "scrolling:",self.widgets[idx].scrolling
        #if self.widgets[idx].scrolling:
        #    return
        self.widgets[idx].set_sbvalue( self.pulse.sinks[idx].volume.values[0] )
        name = "Default"
        if self.pulse.sinks.has_key(idx):
            name = self.pulse.sinks[idx].name
        self.widgets[idx].set_desc(name)
        
        name = "Default"
        if self.pulse.clients.has_key(self.pulse.sinks[idx].client):
            name = self.pulse.clients[self.pulse.sinks[idx].client].name
        self.widgets[idx].set_label( name + " [#"+"%d"%idx+"] ")
        
    def destroy(klass, widget=None):
        #print "destroy signal occurred", widget
        klass.pulse.pulse_close()
        gtk.main_quit()
        
    def sb_valchanged(self,idx,val):
        #print "Scrolled:", idx, val
        cvol = pa_cvolume() 
        cvol.channels = self.pulse.sinks[idx].volume.channels
        
        vol = int(math.floor(val)) #& 0xFFFF
        for i in range(0,cvol.channels):
            cvol.values[i] = vol
            
        self.pulse.op_set_sink_input_volume(idx, POINTER(pa_cvolume)(cvol))
        
        #print cvol
        
    def event_cb(self,e, t,idx):
        #e = event & PA_SUBSCRIPTION_EVENT_FACILITY_MASK
        #t = (event & PA_SUBSCRIPTION_EVENT_TYPE_MASK)
        
        #print "Event:", e, t
        #self.lock.acquire(True)
        try:
            if e == PA_SUBSCRIPTION_EVENT_SINK_INPUT:
                if  t == PA_SUBSCRIPTION_EVENT_REMOVE:
                    print "Remove sink", self.pulse.sinks[idx].name
                    self.removesink(idx)
                    
                if t == PA_SUBSCRIPTION_EVENT_NEW:
                    print "New sink" , self.pulse.sinks[idx].name
                    self.addsink(idx)
                    
                if t == PA_SUBSCRIPTION_EVENT_CHANGE:
                    print "Change sink" , self.pulse.sinks[idx].name
                    self.changesink(idx)
        finally:
            #self.lock.release()
            pass
    


if __name__ == "__main__":
    #sys.settrace(traceit)
    import signal
    signal.signal(SIGPIPE,SIG_IGN)
    gtk.gdk.threads_init()
    pvol = Gui()
    gtk.main()
